package com.wei.miaosha.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.wei.miaosha.domain.MiaoshaOrder;
import com.wei.miaosha.domain.MiaoshaUser;
import com.wei.miaosha.domain.OrderInfo;
import com.wei.miaosha.result.CodeMsg;
import com.wei.miaosha.result.Result;
import com.wei.miaosha.service.GoodsService;
import com.wei.miaosha.service.MiaoshaService;
import com.wei.miaosha.service.MiaoshaUserService;
import com.wei.miaosha.service.OrderService;
import com.wei.miaosha.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Created by Weizichen on 2018/9/8.
 * desc:消费者
 */
@Service
public class MQReceiver {
    private static Logger logger = LoggerFactory.getLogger(MQReceiver.class);
    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;

//    @RabbitListener(queues = MQconfig.QUEUE)
//    public void receiver(String message) {
//
//        logger.info("receive message" + message);
//    }
//
//    @RabbitListener(queues = MQconfig.TOPIC_QUEUE1)
//    public void receiverTopic1(String message) {
//        logger.info("receive topicMessage1" + message);
//    }
//
//    @RabbitListener(queues = MQconfig.TOPIC_QUEUE2)
//    public void receiverTopic2(String message) {
//        logger.info("receive topicMessage2" + message);
//    }
//
//    @RabbitListener(queues = MQconfig.HEADER_QUEUE)
//    public void receiverHeader(byte[] message) {
//        logger.info("receive headerMessage" + new String(message));
//    }


    @RabbitListener(queues = MQconfig.MIAOSHA_QUEUE)
    public void receiver(String message) {
        logger.info("receive message" + message);
        MiaoShaMessage miaoShaMessage = JSON.parseObject(message, MiaoShaMessage.class);
        MiaoshaUser user = miaoShaMessage.getUser();
        long goodsId = miaoShaMessage.getGoodsId();

        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        long stockCount = goods.getStockCount();
        //库存数
        if (stockCount <= 0) {
            //库存不足
            return;
        }
        MiaoshaOrder order = orderService.getMiaoshaOrderByGoodsId(user.getId(), goodsId);
        if (order != null) {
            //已经是秒杀到
            return;
        }
        //减库存 下订单 写入秒杀订单
        OrderInfo orderInfo = miaoshaService.miaoSha(user, goods);
      

    }

}
